﻿package com.gamemeal.wave {
	import flash.display.BitmapData;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;
	/**
	 * @author Colin
	 */
	public class WaveUtils {
		static public function getAmplitude(waveAsByte : ByteArray) : Number {
			waveAsByte.position=0;
			
			var amplitude:Number = 0;
			var value:Number,smooth:Number;

			for( var i: int = 0 ; i < 256 ; i++ ){
				value = waveAsByte.readFloat();

				if( i == 0 ) smooth = value;
				else smooth += ( value - smooth ) / 8;
				
				amplitude = Math.max(smooth,amplitude);
			}
			return amplitude;
		}
		
		static public function drawBytesToBitmapData(waveAsByte : ByteArray,ctx : BitmapData):void{
			waveAsByte.position=0;

			var rect : Rectangle = new Rectangle( 0, 0, 1, 0 );
			
			var value: Number;
			var height: Number;

			var smooth: Number;
			
			var origin:uint = 128;
			
			for( var i: int = 0 ; i < 256 ; i++ ){
				value = waveAsByte.readFloat();
				if( i == 0 ) smooth = value;
				else smooth += ( value - smooth ) / 8;
				height = 2 + smooth * 0xf0;
				rect.x = i;
				rect.y = height+origin;
				ctx.setPixel32(rect.x, rect.y, 0xFF000000 );
			}
			
			for(i = 256 ; i < 512 ; i++ ){
				value = waveAsByte.readFloat();
				if( i == 256 ) smooth = value;
				else smooth += ( value - smooth ) / 8;
				height = 2 + smooth * 0xf0;
				rect.x = i-256;
				rect.y = height+origin;
				ctx.setPixel32(rect.x, rect.y, 0xFFFF0000 );
			}
		}
	}
}
